﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace Singleton
{
    public sealed class Singleton
    {
        private static Singleton instance;
        private static readonly Object syncLock = new Object();

        private int id;

        private Singleton() { id = 0; }

        public int ID
        {
            get
            {
                if (id == 0)
                {
                    id = DateTime.Now.Millisecond;
                }

                return id;
            }
        }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncLock)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }
                    }
                }

                return instance;
            }
        }

        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Task.Factory.StartNew((state) =>
                    {
                        Thread.Sleep(new Random().Next(1000, 5000));
                        Console.WriteLine("{0} => {1}", state, Singleton.Instance.ID);
                    }, i);
            }

            Console.WriteLine("Premere un tasto per uscire..");
            Console.ReadKey();
        }
    }
}
